package com.seadragon.app.ksr.dao.jpa;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.seadragon.app.ksr.dao.EventDao;
import com.seadragon.app.ksr.model.Business;
import com.seadragon.app.ksr.model.Event;

@Repository("eventDao")
public class EventDaoJpaImpl extends AbstractJpaDao implements EventDao {

	@Override
	public void save(Event event) {
		entityManager.persist(event);;
	}

	@Override
	public List<Event> findAll() {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Event> cq = cb.createQuery(Event.class);
		Root<Event> root = cq.from(Event.class);
		cq.select(root);
		return entityManager.createQuery(cq).getResultList();
	}

	@Override
	public List<Event> findAllBy(Business business) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Event> cq = cb.createQuery(Event.class);
		Root<Event> root = cq.from(Event.class);
		cq.select(root);
		cq.where(cb.equal(root.get("business"), business));
		return entityManager.createQuery(cq).getResultList();
	}

	@Override
	public Event findById(long id) {
		return entityManager.find(Event.class, id);
	}

	@Override
	public List<Event> findAll(int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Event> cq = cb.createQuery(Event.class);
		Root<Event> root = cq.from(Event.class);
		cq.select(root);
		TypedQuery<Event> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}

	@Override
	public List<Event> findAllBy(Business business, int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Event> cq = cb.createQuery(Event.class);
		Root<Event> root = cq.from(Event.class);
		cq.select(root);
		TypedQuery<Event> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}

	@Override
	public Event update(Event event) {
		entityManager.merge(event);
		return event;
	}

}
